package com.manor.dynamic.views

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import com.manor.common.utils.*
import com.bumptech.glide.Glide
import com.manor.dynamic.R
import com.manor.common.CommonAppConfig
import com.manor.dynamic.inter.VoicePlayCallBack
import com.manor.im.utils.VoiceMediaPlayerUtil
import kotlinx.android.synthetic.main.view_audio.view.*
import java.io.File

class AudioMp3View : RelativeLayout {


    private var mVoiceMediaPlayerUtil: VoiceMediaPlayerUtil? = null
    protected var mDownloadUtil: DownloadUtil? = null
    protected var mVoicePlayCallBack: VoicePlayCallBack? = null
    private var mVoicePlayTime: Int = 0
    private var mVoiceSumTime: Int = 0
    var isPlaying: Boolean = false

    init {
        LayoutInflater.from(context).inflate(R.layout.view_audio, this)
    }

    var mp3: String = ""

    constructor(context: Context) : super(context) {}
    constructor(context: Context, mp3: String) : super(context) {
        this.mp3 = mp3
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {}


    /**
     * 播放语音
     */
    fun playVoice(voiceLink: String) {
        if (TextUtils.isEmpty(voiceLink)) {
            return
        }
        isPlaying = true
        Glide.with(context)
                .asGif()
                .load(R.mipmap.community_audio_icon)
                .into(im_vcoice)
        val fileName = MD5Util.getMD5(voiceLink)
        val path = CommonAppConfig.VOICE_PATH + fileName
        val file = File(path)
        if (file.exists()) {
            playVoiceFile(file)
        } else {
            if (mDownloadUtil == null) {
                mDownloadUtil = DownloadUtil()
            }

            mDownloadUtil?.download("voice", CommonAppConfig.VOICE_PATH, fileName, voiceLink,
                    object : DownloadUtil.Callback {
                        override fun onSuccess(file: File) {

                            playVoiceFile(file)
                        }

                        override fun onProgress(progress: Int) {

                        }

                        override fun onError(e: Throwable) {
                            ToastUtil.show(WordUtil.getString(R.string.video_play_error))
                            isPlaying = false
                            if (mVoicePlayCallBack != null) {
                                mVoicePlayCallBack?.onPlayAutoEnd()
                            }
                        }
                    })
        }
    }

    open fun setTextLeng(leng: String) {
        if (leng != null) {
            try {

                val a = Integer.parseInt(leng)
                mVoicePlayTime = a
                mVoiceSumTime = a
            } catch (e: NumberFormatException) {

                e.printStackTrace()

            }

        }
        tv_length.setText(mVoicePlayTime.toString() + "s")
    }

//    override fun setOnClickListener(l: OnClickListener?) {
//        super.setOnClickListener(l)
//        if (mp3 != this.tag.toString()) {
//            stopVoice()
//            playVoice(this.tag.toString())
//            mp3 = this.tag.toString()
//        }
//
//    }

    /**
     * 停止播放语音
     */
    fun stopVoice() {
        if (mVoiceMediaPlayerUtil != null) {
            mVoiceMediaPlayerUtil?.stopPlay()
        }
        isPlaying = false
        mVoicePlayCallBack?.onPlayEnd()
        mHandler?.removeMessages(0)
        tv_length.setText(mVoiceSumTime.toString() + "s")
        try {
            Glide.with(im_vcoice.context).load(R.mipmap.pic_audio).into(im_vcoice)
        }catch ( e:IllegalArgumentException){

        }

        mp3 = ""
    }

    // 播语音
    @SuppressLint("HandlerLeak")
    private fun playVoiceFile(file: File) {

        if (mHandler == null) {
            mHandler = object : Handler() {
                override fun handleMessage(msg: Message) {
                    super.handleMessage(msg)
                }
            }
        }
        if (mVoiceMediaPlayerUtil == null) {
            mVoiceMediaPlayerUtil = VoiceMediaPlayerUtil(context)
            mVoiceMediaPlayerUtil?.setActionListener(VoiceMediaPlayerUtil.ActionListener {
                L.e("---show-onPlayAutoEnd-")

                Glide.with(im_vcoice.context).load(R.mipmap.pic_audio).into(im_vcoice)
                mp3 = ""
                tv_length.setText(mVoiceSumTime.toString() + "s")
                isPlaying = false
                if (mHandler != null) {
                    mHandler?.removeMessages(0)
                }

                if (mVoicePlayCallBack != null) {

                    mVoicePlayCallBack?.onPlayAutoEnd()
                }
            })
        }
        mVoiceMediaPlayerUtil?.startPlay(file.absolutePath)
        mHandler?.sendEmptyMessageDelayed(0, 1000)
        mVoicePlayCallBack?.onPlayStart()
    }

    private var mHandler: Handler? = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            mVoicePlayTime--
            if (mVoicePlayTime > 0) {
                this?.sendEmptyMessageDelayed(0, 1000)
                tv_length.setText(mVoicePlayTime.toString() + "s")
            } else {
                if (mVoicePlayTime == 0) {
                    mVoicePlayTime = mVoiceSumTime
                }
            }
        }
    }

    fun resetView() {

        mVoicePlayTime = mVoiceSumTime

        if (mHandler != null) {
            mHandler?.removeMessages(0)
        }
        isPlaying = false
      //  Glide.with(context).resumeRequests()
        if (mVoiceMediaPlayerUtil != null) {
            mVoiceMediaPlayerUtil?.stopPlay()
        }
    }

    fun release() {
  //      Glide.with(context).resumeRequests()
        if (mVoiceMediaPlayerUtil != null) {
            mVoiceMediaPlayerUtil?.destroy()
        }
        mVoiceMediaPlayerUtil = null
        if (mHandler != null) {
            mHandler?.removeCallbacksAndMessages(null)
            mHandler = null
        }


    }
}
